package com.umgsai.aop.level2;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

/**
 * Created by shangyidong on 17/6/29.
 */
public class ArithmeticCaculatorProxy {
    //要代理的对象
    private ArithmeticCalculator target;

    public ArithmeticCaculatorProxy(ArithmeticCalculator target){
        this.target = target;
    }

    public ArithmeticCalculator getProxy() {
        ArithmeticCalculator proxy = null;
        ClassLoader classLoader = target.getClass().getClassLoader();
        Class[] interfaces = new Class[]{ArithmeticCalculator.class};
        InvocationHandler handler = new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                String methodName = method.getName();
                System.out.println("The method " + methodName + " begins with" + Arrays.asList(args));
                System.out.println("Invoke...");
                //执行方法
                Object result = method.invoke(target, args);
                //日志
                System.out.println("The method " + methodName + " ends with " + result);
                return result;
            }
        };
        proxy = (ArithmeticCalculator) Proxy.newProxyInstance(classLoader, interfaces, handler);
        return proxy;
    }
}
